#! /bin/sh

libName=""
dirRoot=""
dirBuild=""
headers=""
export LC_COLLATE="C"
export LC_CTYPE="C"
export LC_TIME="C"
export LC_ALL="C"
export LANGUAGE="en"
export LANG="en"

for arg in "${@}" ; do
	case ${arg} in
		--lib-name=*)    libName="$(echo ${arg} | sed 's;--lib-name=;;')" ;;
		--dir-root=*)    dirRoot="$(echo ${arg} | sed 's;--dir-root=;;')" ;;
		--dir-build=*)   dirBuild="$(echo ${arg} | sed 's;--dir-build=;;')" ;;
		--headers=*)     headers="$(echo ${arg} | sed 's;--headers=;;')" ;;
		*)
			echo "unknown option: ${arg}"
			exit 1
		;;
	esac
done

if [ -z "${libName}" -o -z "${dirRoot}" -o -z "${dirBuild}" -o -z "${headers}" ] ; then
	printf "%b\n" "Core settings not found!"
	exit 1
fi

if [ "x${VERBOSE}" != "x" ] ; then
	echo "libName    = ${libName}"
	echo "dirRoot    = ${dirRoot}"
	echo "dirBuild   = ${dirBuild}"
	echo "headers    = [${headers}]"
fi

umask 022

libNameUC="$(echo ${libName} | tr [a-z] [A-Z])"

cd ${dirRoot}

dirHeaders="${dirBuild}/include/${libName}"

for file in ${headers}; do
	if grep -q -w 'YAAL_PRIVATE_IMPLEMENTATION_DETAIL' "${file}"; then
		continue
	fi
	mkdir -p "${dirHeaders}/$(dirname ${file})"
	awk -f - ${file} > ${dirHeaders}/${file} << EOF
/^#\\t*include "/ {
	match(\$0, "#\\t*include");
	printf "%s", substr( \$0, RSTART, RLENGTH );
	match(\$0, "\"[a-z_./-]+");
	printf " <${libName}/%s>\\n", substr(\$0, RSTART + 1, RLENGTH - 1) }
!/^#\\t*include "/
EOF
	touch -r ${file} ${dirHeaders}/${file}
done

configSrcPath="${dirBuild}/config.hxx"

if [ ! -f "${configSrcPath}" ] ; then
	configSrcPath="${dirRoot}/config.hxx"
fi

sed -e "s/define[ \t]*PACKAGE_/define ${libNameUC}_PACKAGE_/g" \
	-e "s/define[ \t]*SYSCONFDIR/define ${libNameUC}_SYSCONFDIR/g" \
	-e "s/define[ \t]*LOCALSTATEDIR/define ${libNameUC}_LOCALSTATEDIR/g" \
	-e "s/define[ \t]*SHAREDSTATEDIR/define ${libNameUC}_SHAREDSTATEDIR/g" \
	-e "s/define[ \t]*BINDIR/define ${libNameUC}_BINDIR/g" \
	-e "s/define[ \t]*LIBDIR/define ${libNameUC}_LIBDIR/g" \
	-e "s/define[ \t]*LIBEXECDIR/define ${libNameUC}_LIBEXECDIR/g" \
	-e "s/define[ \t]*DATADIR/define ${libNameUC}_DATADIR/g" \
	-e 's/#define[ \t]*LIB_INFIX.*/#undef LIB_INFIX/g' "${configSrcPath}" > ${dirHeaders}/config.hxx

proto="$(find ${dirHeaders} ! -path "${dirHeaders}/${libName}.hxx" ! -name 'config.hxx' -type f | head -1 | sed -e "s@${dirHeaders}/@@")"
protoTag="$(echo ${proto} | sed -e 's@.*/\([^\.]*\).*@\1@')"

head -1 ${dirHeaders}/${proto} > ${dirHeaders}/${libName}.hxx

cat << EOF >> ${dirHeaders}/${libName}.hxx

#ifndef ${libNameUC}_${libNameUC}_HXX_INCLUDED
#define ${libNameUC}_${libNameUC}_HXX_INCLUDED 1

EOF

find ${dirHeaders} ! -path "${dirHeaders}/${libName}.hxx" -type f | sed -E -e "s@.*(${libName}(/[^/]*){0,2}/[^/]*[.]hxx)@#include <\1>@g" | sort >> ${dirHeaders}/${libName}.hxx

cat << EOF >> ${dirHeaders}/${libName}.hxx

#endif /* #ifndef ${libNameUC}_${libNameUC}_HXX_INCLUDED */

EOF

